package com.dfd.oauth2.rbac2.config.service;

import com.dfd.oauth2.rbac2.domain.TbPermission;
import com.dfd.oauth2.rbac2.domain.TbUser;
import com.dfd.oauth2.rbac2.service.TbPermissionService;
import com.dfd.oauth2.rbac2.service.TbUserService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/*
 *文件名: UserDetailsServiceImpl
 *创建者: 东东
 *创建时间:2021/8/30 10:18
 *描述: 自定义认证授权实现类
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private TbUserService userService;
    @Autowired
    private TbPermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        TbUser tbUser = userService.getByUsername(username);
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();
        if (tbUser != null) {
            // 获取用户授权
            List<TbPermission> permissions = permissionService.selectByUserId(tbUser.getId());
            // 声明用户授权
            permissions.stream().forEach(permission -> {
                if (permission != null && permission.getEnname() != null) {
                    GrantedAuthority authority = new SimpleGrantedAuthority(permission.getEnname());
                    grantedAuthorities.add(authority);
                }
            });
        }


        // 由框架完成授权
        return new User(username, tbUser.getPassword(), grantedAuthorities);
    }
}
